<template>
  <div>
    <a-table
      :columns="sortTableColumns"
      :data-source="tableData"
      :pagination="false"
      :loading="loading"
      :id="'sortTable' + tableId"
      style="height:600px;"
      :scroll="{ y: 550 }"
      :row-key="_tableRowKey"
    >
      <template slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </template>
      <template slot="editable" slot-scope="text, record, index">
        <div v-if="record.operability" class="disFlxAC">
          <a-input
            v-model="record.displayName"
            @blur="editDisplayName(record)"
            :id="'displayNameInput' + record.id"
            style="text-align: center;width:88px;"
          />
        </div>
        <div v-else class="disFlxAC flexCenter">
          <div>{{ text }}</div>
          <a-icon v-if="locationRule === 'IMPORT'" class="_p-5 cup" type="edit" @click="_toggle(record)" />
        </div>
      </template>
      <template slot="addAction" slot-scope="text, record, index">
        <!-- 占位状态 -->
        <template v-if="record.userId === -1">
          <a-tag color="pink" class="_mr-1 _ml-1" @click.stop="deleteUser(record)">取消占位</a-tag>
          <a-tag color="blue" class="_mr-1 _ml-1" @click.stop="openSelectUserModel(3, record.id)">添加人员</a-tag>
        </template>
        <!-- 无人员 -->
        <template v-else-if="!record.userId">
          <a-tag color="green" class="_mr-1 _ml-1" @click.stop="lockSeat(record)">立即占位</a-tag>
          <a-tag color="blue" class="_mr-1 _ml-1" @click.stop="openSelectUserModel(2, record.id)">添加人员</a-tag>
        </template>
        <div v-else class="disFlxAC flexCenter">
          <span class="ov-1">{{ text || '' }}</span>
          <a-tooltip title="移除人员">
            <a-icon class="_pl-10 linh-20 flexS0" type="close" @click.stop="deleteUser(record)" />
          </a-tooltip>
        </div>
      </template>
      <template slot="signStatus" slot-scope="text, record, index">
        <span v-if="text">{{ text == signStatusEnum.STAY ? '未签到' : '已签到' }}</span>
        <span v-else>-</span>
      </template>
      <template slot="action" slot-scope="text, record, index">
        <a-tooltip title="移除位置">
          <a-button type="primary" ghost @click.stop="deleteRow(record, index)">
            移除位置
          </a-button>
          <!-- <a-icon class="_pl-5 _pr-5 colorZS" type="delete" @click.stop="deleteRow(record, index)" /> -->
        </a-tooltip>
        <a-tooltip class="_ml-8" title="换位置">
          <a-button type="primary" :disabled="!record.userId" ghost @click.stop="openChangePlaceModel(record)">
            换位置
          </a-button>
        </a-tooltip>
        <a-tooltip class="_ml-8" title="上移一行">
          <a-button type="primary" ghost @click.stop="upRow(index)">
            上移
          </a-button>
          <!-- <a class="_pl-5 _pr-5" @click.stop="upRow(index)"><a-icon type="arrow-up"/></a> -->
        </a-tooltip>
        <a-tooltip class="_ml-8" title="下移一行">
          <a-button type="primary" ghost @click.stop="downRow(index)">
            下移
          </a-button>
          <!-- <a class="_pl-5 _pr-5" @click.stop="downRow(index)"><a-icon type="arrow-down"/></a> -->
        </a-tooltip>
      </template>
    </a-table>
    <div class="fontTC _pt-14 _pb-10">
      <a-tag color="blue" class="cup _pl-30 _pr-30 linh-25" @click.stop="addRow()">
        添加
      </a-tag>
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import { sortTableColumns } from './columns.js'
import {
  activityArrangeAddSeat,
  activityArrangeDelSeat,
  activityArrangeSwapSeat,
  activityArrangeClear,
  activityArrangeLockSeat,
  activityUpdateSeatName
} from '@/api/activity/activity.js'
import { cloneDeep } from 'lodash-es'
import { signStatusEnum } from '@/enums/activity'

export default {
  props: {
    tableId: {
      type: Number
    },
    // 位置排座方式 AUTO 自动生成 IMPORT 导入
    locationRule: {
      type: String,
      default: 'AUTO'
    },
    tableData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      sortTableColumns,
      loading: false,
      oldDisplayName: undefined,
      signStatusEnum
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.initSortable()
      }, 500)
    })
  },
  methods: {
    _toggle(row) {
      this.oldDisplayName = row.displayName
      this.$set(row, 'operability', true)
      this.$nextTick(() => {
        const tbList = this.$el.querySelector(`#displayNameInput${row.id}`)
        tbList.focus() // 输入款自动聚焦
      })
    },
    // 修改位置编号
    editDisplayName(row) {
      const _this = this
      row.operability = false
      if (row.displayName === _this.oldDisplayName) return
      activityUpdateSeatName({ id: row.id, name: row.displayName })
    },
    openChangePlaceModel(data) {
      this.$emit('openChangePlaceModel', data)
    },
    // 选择人员 type 1: 批量选择人员 2.指定座位添加人员 3.指定座位添加人员(座位为占座)
    openSelectUserModel(type, seatId) {
      this.$emit('openSelectUserModel', type, this.tableId, seatId)
    },
    // 删除一行 -前端静默更新
    deleteRow(row, index) {
      activityArrangeDelSeat({ seatId: row.id }).then(() => {
        this.tableData.splice(index, 1)
        this.$emit('resetHead') // 刷新头部信息
      })
    },
    // 清空位置,移除人员 -前端静默更新
    deleteUser(row) {
      activityArrangeClear({ seatId: row.id }).then(() => {
        row.userId = null
        row.userName = null
        row.userPosition = null
        row.userCompanyName = null
        this.$emit('resetHead') // 刷新头部信息
      })
    },
    // 占位 -前端静默更新
    lockSeat(row) {
      activityArrangeLockSeat({ seatId: row.id }).then(() => {
        row.userId = -1
        this.$emit('resetHead') // 刷新头部信息
      })
    },
    // 增加一行 -根据后端返回静默更新
    addRow() {
      activityArrangeAddSeat({ groupId: this.tableId }).then(res => {
        this.tableData.push(res.data)
        const tbList = this.$el.querySelectorAll(`.ant-table-body`)
        this.$nextTick(() => {
          const currentTable = tbList[0]
          currentTable.scrollTop = currentTable.scrollHeight // 滚动到最底部
        })
        this.$emit('resetHead') // 刷新头部信息
      })
    },
    // 上移一行 -前端静默更新
    async upRow(index) {
      if (index !== 0) {
        this._sortFn(index, index - 1)
      }
    },
    // 下移一行 -前端静默更新
    async downRow(index) {
      if (index + 1 !== this.tableData.length) {
        this._sortFn(index, index + 1)
      }
    },
    // 拖动方法, 请勿在表格添加fixed属性,否则出现bug -前端静默更新
    initSortable() {
      const _this = this
      const mytb = document.querySelector(`#sortTable${_this.tableId} tbody`)
      if (!mytb) return
      new Sortable(mytb, {
        handle: '.ant-table-row',
        animation: 150,
        ghostClass: 'blue-background-class',
        async onEnd({ oldIndex, newIndex }) {
          if (oldIndex === newIndex) return
          _this._sortFn(oldIndex, newIndex)
        }
      })
    },
    // 表格排序
    _sortFn(oldIndex, newIndex) {
      this.loading = true // 此处不加loading, 无效交换的拖拽场景,表格不会刷新
      const oldRow = cloneDeep(this.tableData[oldIndex])
      const newRow = cloneDeep(this.tableData[newIndex])
      if (!oldRow.userId && !newRow.userId) {
        // 都无人员,拦截不调用接口
        this.loading = false
        return
      }
      this.tableData[oldIndex].userId = newRow.userId
      this.tableData[oldIndex].userName = newRow.userName
      this.tableData[oldIndex].userPosition = newRow.userPosition
      this.tableData[oldIndex].userCompanyName = newRow.userCompanyName
      this.tableData[oldIndex].signStatus = newRow.signStatus
      
      this.tableData[newIndex].userId = oldRow.userId
      this.tableData[newIndex].userName = oldRow.userName
      this.tableData[newIndex].userPosition = oldRow.userPosition
      this.tableData[newIndex].userCompanyName = oldRow.userCompanyName
      this.tableData[newIndex].signStatus = oldRow.signStatus
      this.loading = false
      activityArrangeSwapSeat({ seatId: oldRow.id, targetSeatId: newRow.id }).catch(() => {
        this.tableData[oldIndex] = oldRow
        this.tableData[newIndex] = newRow
      })
    },
    // 表格唯一Key值
    _tableRowKey(row) {
      return `${row.id}-${new Date().getTime()}-${row.userId || 0}`
    }
  }
}
</script>

<style lang="less" scoped></style>
